<?php
namespace app\souther\controller;

use think\Controller;
use think\File;
use think\Request;
/**
 * 
 */
class Upload extends Controller
{
	/**
     * [uploadOne  webUploader上传图片]
     * @author [南风]
     * @param string $folder 保存图片文件夹名
     */
    public function webUploaderImages($folder = 'images')
    {

        //获取配置
        $config = get_config();
		
        //保存本地
        if($config['upload_mode']=='1'){
            $folder = !empty(input('param.folder')) ? input('param.folder') : $folder;

            $file = request()->file('file');

            $info = $file->move('uploads/'.$folder);

            if ($info && $info->getPathname()) {

            	
                $path = '/' . $info->getPathname();
                
                return admin_json(1, 'OK', ['path' => $path]);
            } else {
                return admin_json(-1, $file->getError());
            }
        }

        //保存七牛云
        else if($config['upload_mode']=='2'){
            if (empty($_FILES['file']['tmp_name'])) {
                exception(['msg' => "上传文件发生错误", 'code' => 0]);
            } else {

                //获取上传的临时文件
                $file = request()->file('file');
                
                // 要上传图片的本地路径

                $filePath = $file->getRealPath();

                $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                // 上传到七牛后保存的文件名
                $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;

                require_once APP_PATH . '/../vendor/Qiniu/autoload.php';

                // 需要填写你的 Access Key 和 Secret Key
                $accessKey = $config['qiniu_accesskey'];
                $secretKey = $config['qiniu_secretkey'];
                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);

                // 要上传的空间
                $bucket = $config['qiniu_bucket'];
                $domain = $config['qiniu_domain'];

                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new UploadManager();

                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

                if ($err !== null) {
                    $this->error($err);
                    return admin_json(0, $err, '');
                } else {
                    //返回图片的完整URL
                    return admin_json(1, 'OK', ['path'=>$domain.'/'.$ret['key']]);
                }
            }
        }else{
            return admin_json(-1, '请选择保存文件的方式', '');
        }
    }
}